//
//  EnterCostCommitVC.m
//  KuWoCan
//
//  Created by hwd on 17/4/12.
//  Copyright © 2017年 hwd. All rights reserved.
//

#import "EnterCostCommitVC.h"

#import "LabTextViewCell.h"
#import "NWSaleApplyRequest.h"
#import "PhotoManageCell.h"
#import "orderTotalCell.h"
#import "CargoCell.h"
#import "CargoChooseVC.h"

#define kECParaDicKey_name @"name"
#define kECParaDicKey_desCribe @"supermarketProfiles"//1 修改添加
#define kECParaDicKey_address @"address"
#define kECParaDicKey_phone @"phone"
#define kECParaDicKey_workPhone @"workPhone"//4
#define kECParaDicKey_purchase @"purchase"
#define kECParaDicKey_storeNumber @"storeNumber"
#define kECParaDicKey_annualOperation @"annualOperation"
#define kECParaDicKey_similarBrands @"similarBrands"
#define kECParaDicKey_annualSales @"annualSales"
#define kECParaDicKey_totalExpenses @"totalExpenses"
#define kECParaDicKey_costStatement @"costStatement"//12
#define kECParaDicKey_photoList @"photoList"
#define kECParaDicKey_scenePhotoList @"scenePhotoList"
#define kECParaDicKey_paperPhotoList @"paperPhotoList"

#define kECParaDicKey_approachAProductList @"approachAProductList"
#define kECParaDicKey_kwApproachExamineProduct @"approachEProductList"

@interface EnterCostCommitVC () <UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) TPKeyboardAvoidingTableView *tabView;
/** 参数字典 */
@property (nonatomic,strong) NSMutableDictionary *paraDic;
/** 参数 */
@property (nonatomic,copy) NSArray *keysArr;
/** Cell标题 */
@property (nonatomic,copy) NSArray *leftStrArr;

//进场申请选中上传的图片数组
@property (nonatomic, copy) NSMutableArray<NSDictionary *> *submitPictureArr;

/////修改添加
@property (nonatomic,strong)NSMutableArray *cargoListArr;//商品数组
@property (nonatomic,strong)NSMutableArray *paraDataArr;
@property (nonatomic,strong)NSMutableArray *objectParaArr;

@property(nonatomic,assign)NSInteger totalBox;//总数
@property(nonatomic,assign)CGFloat totalPrice;//总价
@property (nonatomic,assign) BOOL isNotDetailModel_Cargo;


@end

@implementation EnterCostCommitVC
#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    _cargoListArr = [[NSMutableArray alloc]init];
    _paraDataArr = [[NSMutableArray alloc]init];
    _objectParaArr = [[NSMutableArray alloc]init];
    _photoArr =  [[NSMutableArray alloc]init];
    [self setUpUI];
    if (_isChangeInfo)
    {
        [self prepareDataForChangeOrder];
    }

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Config UI
- (void)setUpUI
{
    self.view.backgroundColor = [UIColor whiteColor];

    if (self.moduleType == HomeModuleTypeEA) {
        self.title = @"进场费用详情";
    } else {
        self.title = @"进场费用核销详情";
    }
    
    _tabView = [[TPKeyboardAvoidingTableView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) style:UITableViewStyleGrouped];
    _tabView.backgroundColor = KwBgColor;
    _tabView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tabView.estimatedRowHeight = 40.0;
    _tabView.rowHeight = UITableViewAutomaticDimension;
    _tabView.delegate = self;
    _tabView.dataSource = self;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cancelKeyboard)];
    tap.cancelsTouchesInView = NO;
    [_tabView addGestureRecognizer:tap];
    [self.view addSubview:_tabView];
    [_tabView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@0);
        make.left.right.equalTo(@0);
        make.bottom.equalTo(@-55);
    }];

    //创建底部按钮
    UIButton *confirmBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [confirmBtn setBackgroundColor:KwBlueColor];
    [confirmBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [confirmBtn setTitle:_isSubmit ? @"提交申请" : @"确认修改" forState:UIControlStateNormal];
    confirmBtn.titleLabel.font = KwFont(16.0);
    [confirmBtn addTarget:self action:@selector(startPlaceAnOrder:) forControlEvents:UIControlEventTouchUpInside];
    confirmBtn.layer.masksToBounds = YES;
    confirmBtn.layer.cornerRadius = 5.0;
    [self.view addSubview:confirmBtn];
    [confirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(@-5);
        make.top.equalTo(_tabView.mas_bottom).offset(1);
        make.left.equalTo(@5);
        make.right.equalTo(@-5);
    }];

}

- (void)cancelKeyboard {
    [self.view endEditing:YES];
}
#pragma mark - Load data
- (void)prepareDataForChangeOrder  //修改订单进入后 显示传来的数据
{
    [self.paraDic setValue:_detailInfoModel.name  forKey:kECParaDicKey_name];
    [self.paraDic setValue:_detailInfoModel.supermarketProfiles  forKey:kECParaDicKey_desCribe];//
    [self.paraDic setValue:_detailInfoModel.address forKey:kECParaDicKey_address];
    [self.paraDic setValue:_detailInfoModel.workPhone forKey:kECParaDicKey_workPhone];//
    [self.paraDic setValue:_detailInfoModel.phone forKey:kECParaDicKey_phone];
    [self.paraDic setValue:_detailInfoModel.purchase forKey:kECParaDicKey_purchase];
    [self.paraDic setValue:_detailInfoModel.storeNumber forKey:kECParaDicKey_storeNumber];
    [self.paraDic setValue:_detailInfoModel.annualOperation forKey:kECParaDicKey_annualOperation];
    [self.paraDic setValue:_detailInfoModel.similarBrands forKey:kECParaDicKey_similarBrands];
    [self.paraDic setValue:_detailInfoModel.annualSales forKey:kECParaDicKey_annualSales];
    [self.paraDic setValue:_detailInfoModel.totalExpenses forKey:kECParaDicKey_totalExpenses];
    [self.paraDic setValue:_detailInfoModel.costStatement forKey:kECParaDicKey_costStatement];
    
    //图片参数处理
    if (_moduleType == HomeModuleTypeEA)
    {
        _photoArr = [NSMutableArray arrayWithArray:_detailInfoModel.photoList];
        [self prepareDataForAddPicParaWithKey:kECParaDicKey_photoList pics:_photoArr];
    }
    else
    {
        _scenePhotoArr = [NSMutableArray arrayWithArray:_detailInfoModel.scenePhotoList];
        [self prepareDataForAddPicParaWithKey:kECParaDicKey_scenePhotoList pics:_scenePhotoArr];

        _paperPhotoArr = [NSMutableArray arrayWithArray:_detailInfoModel.paperPhotoList];
        [self prepareDataForAddPicParaWithKey:kECParaDicKey_paperPhotoList pics:_paperPhotoArr];
    }

    if (_moduleType == HomeModuleTypeEC)
    {
        _cargoListArr =  _detailInfoModel.kwApproachExamineProduct.copy;
    }
    else
    {
        _cargoListArr =  _detailInfoModel.kwApproachApplicationProduct.copy;
    }

    if (_cargoListArr && _cargoListArr.count > 0)
    {
        for (int i = 0; i<_cargoListArr.count; i++)
        {
            SADetailCargoModel *model = _cargoListArr[i];
            [_paraDataArr addObject:@{kOrderItemPara_Key_ProductAttributeId:model.productAttributeId,kOrderItemPara_Key_ProductName:[NSString stringWithFormat:@"%@,%@,%@",model.kwProductAttribute.product.productName,model.kwProductAttribute.tasteStr,model.kwProductAttribute.specificationsStr],kOrderItemPara_Key_Price:model.kwProductAttribute.price,kOrderItemPara_Key_Quantity:model.quantity}];
        }
        NSString *dataStr = [CommonTool beJsonStrWithObj:_paraDataArr];
        if (_moduleType == HomeModuleTypePC)
        {
            [_paraDic setValue:dataStr forKey:kECParaDicKey_kwApproachExamineProduct];
        }
        else
        {
            [_paraDic setValue:dataStr forKey:kECParaDicKey_approachAProductList];
        }
    }
    //合计
    NSInteger aTotalBox = 0;
    CGFloat aTotalPrice = 0;
    for (int i = 0; i<_cargoListArr.count; i++)
    {
        SADetailCargoModel *model = _cargoListArr[i];
        aTotalBox = aTotalBox + [model.quantity integerValue];
        aTotalPrice = aTotalPrice + [model.kwProductAttribute.price floatValue]*[model.quantity integerValue];
    }
    _totalBox = aTotalBox;
    _totalPrice = aTotalPrice;

}

- (void)prepareDataForAddPicParaWithKey:(NSString *)key pics:(NSMutableArray *)pics
{
    NSMutableArray *picParaArr = [NSMutableArray array];

    if (pics && pics.count > 0)
    {
        for (PicListModel *model in pics)
        {
            [picParaArr addObject:@{@"type":model.type,@"title":model.title,@"imgs":model.imgs}];
        }
    }
    NSString *picParaStr = [CommonTool beJsonStrWithObj:picParaArr];
    [self.paraDic setValue:picParaStr forKey:key];
}


#pragma mark - Data request


#pragma mark - Registration notice and release


#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (_moduleType == HomeModuleTypeEC) {
        if (_isShowHXBZ) {
            return 5;
        }
        return 4;
    } else {
        if (_isShowHXBZ) {
            return 4;
        }
        return 3;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        if (_cargoListArr.count>0) {
            return  _cargoListArr.count+1;
        }else
        {
            return  _cargoListArr.count+2;
        }
        
      
    } else  if (_isShowHXBZ && section == 4 && _moduleType == HomeModuleTypeEC) {
        return 1;
    } else  if (_isShowHXBZ && section == 3 && _moduleType == HomeModuleTypeEA) {
        return 1;
    }
    else if (section == 1){
        return self.leftStrArr.count;
    }
    else {
        return 1;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (_isShowHXBZ && section == 4 && _moduleType == HomeModuleTypeEC) {
        return 50;
    } else  if (_isShowHXBZ && section == 3 && _moduleType == HomeModuleTypeEA) {
        return 50;
    }
    return 0.0001;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (_isShowHXBZ && section == 4 && _moduleType == HomeModuleTypeEC) {
        UIView *headView = [self createHeaderViewWithTitle:@"费用核销标准"];
        return headView;
    } else  if (_isShowHXBZ && section == 3 && _moduleType == HomeModuleTypeEA) {
        UIView *headView = [self createHeaderViewWithTitle:@"费用核销标准"];
        return headView;;
    }
        return nil;
    
}

- (UIView *)createHeaderViewWithTitle:(NSString *)title
{
    UIView *headView = [UIView new];
    headView.backgroundColor = [UIColor whiteColor];
    UILabel *lab = [UILabel new];
    lab.text = title;
    lab.textColor = [UIColor blackColor];
    lab.font = KwFont(15);
    [headView addSubview:lab];
    [lab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(headView.mas_left).offset(20);
        make.top.equalTo(headView).offset(15);
        make.height.equalTo(@15);
    }];
    
    UIView *lineView = [UIView new];
    lineView.frame = CGRectMake(0, 50, self.view.bounds.size.width, 1.5);
    lineView.backgroundColor = KwGaryColor;
    [headView addSubview:lineView];
    return headView;
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.0001;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *labTextFieldCell_ID = [NSString stringWithFormat:@"LabTextFieldCell%ld%ld",indexPath.section,indexPath.row];
    static NSString *photoManageCell_ID = @"PhotoManageCell";

    if (indexPath.section == 0)
    {
        //酷我商城
        if (_cargoListArr &&_cargoListArr.count>0)
        {
            if (indexPath.row == 0)
            {
                UITableViewCell *cell;
                //这一行为 酷我商城
                cell = [tableView dequeueReusableCellWithIdentifier:@"tempCell_Id"];
                if (!cell) {
                    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"tempCell_Id"];
                    [self createCellUIWithCell:cell];
                }
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                return cell;
            }
            else if(indexPath.row == _cargoListArr.count+1)
            {
                orderTotalCell *cell;
                //这一行为合计
                cell = [tableView dequeueReusableCellWithIdentifier:@"cell2"];
                if (!cell)
                {
                    cell = [[orderTotalCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell2"];
                }
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.oTotalParaLab.text = [NSString stringWithFormat:@"¥%.2f",_totalPrice];
                cell.oNumberLab.text = [NSString stringWithFormat:@"共%ld件商品",(long)_totalBox];
                return cell;
            }
            else
            {
                CargoCell *cell;
                //其余为商品展示
                cell = [tableView dequeueReusableCellWithIdentifier:@"cell3"];
                if (!cell)
                {
                    cell = [[CargoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell3"];
                }
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                if (_isChangeInfo)
                {
                    if (!_isNotDetailModel_Cargo)
                    {
                        if (_cargoListArr && _cargoListArr.count>0)
                        {
                            SADetailCargoModel *model = _cargoListArr[indexPath.row-1];
                            cell.saCargoModel = model;
                        }
                    }
                    else
                    {
                        if (_cargoListArr && _cargoListArr.count>0)
                        {
                            ESSInventoryModel *model = _cargoListArr[indexPath.row-1];
                            cell.model = model;
                        }
                    }
                }
                else
                {
                    if (_cargoListArr && _cargoListArr.count>0)
                    {
                        ESSInventoryModel *model = _cargoListArr[indexPath.row-1];
                        cell.model = model;
                    }
                }
                return cell;
            }
        }else//////////////////////////////////////
        {
            if (indexPath.row == 0) {
                UITableViewCell *cell;
                //这一行为 酷我商城
                cell = [tableView dequeueReusableCellWithIdentifier:@"tempCell_Id"];
                if (!cell) {
                    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"tempCell_Id"];
                    [self createCellUIWithCell:cell];
                }
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                
                return cell;
            }else
            {
                UITableViewCell*cell = [tableView dequeueReusableCellWithIdentifier:@"tempCell3"];
                if (!cell) {
                    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"tempCell3"];
                    UIImageView *img = [UIImageView new];
                    img.image = kImg(@"nodata");
                    [cell addSubview:img];
                    __weak UITableViewCell *weakCell  = cell;
                    [img mas_makeConstraints:^(MASConstraintMaker *make) {
                        make.centerX.equalTo(weakCell.mas_centerX);
                        make.top.equalTo(weakCell.mas_top).offset(30);
                        make.bottom.equalTo(weakCell.mas_bottom).offset(-30);
                        make.size.mas_equalTo(CGSizeMake(150, 120));
                    }];
                }
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                return cell;
            }
        }

    }
    //活动名称
   else if (indexPath.section == 1)
    {
        LabTextViewCell *cell = [tableView dequeueReusableCellWithIdentifier:labTextFieldCell_ID];
        if (!cell)
        {
            cell = [[LabTextViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:labTextFieldCell_ID];
        }
        cell.constStr = self.leftStrArr[indexPath.row];
        NSString *keyStr = self.keysArr[indexPath.row];
        cell.paraStr = [ToolViewViewController isNotNullStr:[self.paraDic objectForKey:keyStr]]?[self.paraDic objectForKey:keyStr]:@" ";
        cell.block = ^(NSString *str){
            [self.paraDic setObject:str forKey:keyStr];
        };
        return cell;
    }
     else  if ((_isShowHXBZ && indexPath.section == 4 && _moduleType == HomeModuleTypeEC) || (_isShowHXBZ && indexPath.section == 3 && _moduleType == HomeModuleTypeEA)) {
         TextViewCell *cell;
         cell = [tableView dequeueReusableCellWithIdentifier:@"cellText2"];
         if (!cell)
         {
             cell = [[TextViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellText2"];
         }
         [cell setUpUIWithTextStr:_mbContect];
         cell.selectionStyle = UITableViewCellSelectionStyleNone;
         cell.textView.editable = NO;
         return cell;
    }
    else
    {
        PhotoManageCell *cell;
        cell = [tableView dequeueReusableCellWithIdentifier:photoManageCell_ID];
        if (!cell)
        {
            cell = [[PhotoManageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:photoManageCell_ID];
        }
        cell.isChange = _isChangeInfo;
        cell.orderId = _orderId;
        cell.isSubmit = _isSubmit;
        cell.vc = self;
        __weak typeof(self) weakSelf = self;
        cell.choosePictureHandle = ^(NSArray<PicListModel *> *picArr) {
            [_photoArr removeAllObjects];
            [weakSelf.submitPictureArr removeAllObjects];
            NSArray *tempArr = picArr;
            if (weakSelf.moduleType == HomeModuleTypeEC) {
                if (indexPath.section == 1) {
                    [_scenePhotoArr removeAllObjects];
                } else {
                    [_paperPhotoArr removeAllObjects];
                }
            }

            NSMutableArray *sceneTempArr = [NSMutableArray array];
            NSMutableArray *paperTempArr = [NSMutableArray array];

            [tempArr enumerateObjectsUsingBlock:^(PicListModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if (weakSelf.moduleType == HomeModuleTypeEC) {
                    if (indexPath.section == 1) {
                        [_scenePhotoArr addObject:obj];
                        [sceneTempArr addObject:[CommonTool beJsonStrWithObj:@{@"type": @"8", @"title": obj.title, @"imgs": obj.imgs}]];
                    } else if (indexPath.section == 2 ) {
                        [paperTempArr addObject:[CommonTool beJsonStrWithObj:@{@"type": @"9", @"title": obj.title, @"imgs": obj.imgs}]];
                        [_paperPhotoArr addObject:obj];
                    }
                }
                [_photoArr addObject:obj];
                [weakSelf.submitPictureArr addObject:@{@"type": @"7", @"title": obj.title, @"imgs": obj.imgs}];
            }];
            if (self.moduleType == HomeModuleTypeEC) {
                [self.paraDic setObject:[CommonTool beJsonStrWithObj:sceneTempArr] forKey:kECParaDicKey_scenePhotoList];
                [self.paraDic setObject:[CommonTool beJsonStrWithObj:paperTempArr] forKey:kECParaDicKey_paperPhotoList];
            }
            if (self.submitPictureArr.count>0) {
                [self.paraDic setObject:[CommonTool beJsonStrWithObj:self.submitPictureArr] forKey:kECParaDicKey_photoList];
            }else
            {
                [self.paraDic setObject:@"" forKey:kECParaDicKey_photoList];
            }
         
        };

        if (_moduleType == HomeModuleTypeEA)
        {
            cell.titleLabel.text = @"进场明细照片管理";
            cell.picType = PicTypeEnterFeeApply_Enter;
            [cell configCell:_photoArr];
            return cell;
        }
        else
        {
            if (indexPath.section == 2)
            {
                cell.titleLabel.text = @"进场明细照片管理";
                cell.picType = PicTypeEnterFeeCheck_Enter;
                [cell configCell:_scenePhotoArr];
                cell.choosePictureHandle = ^(NSArray<PicListModel *> *picArr) {
                    [weakSelf.scenePhotoArr removeAllObjects];
                    _scenePhotoArr = picArr.mutableCopy;
                };

            }
            else
            {
                cell.titleLabel.text = @"票据照片管理";
                cell.picType = PicTypeEnterFeeCheck_Bill;
                [cell configCell:_paperPhotoArr];
                cell.choosePictureHandle = ^(NSArray<PicListModel *> *picArr) {
                    [weakSelf.paperPhotoArr removeAllObjects];
                    _paperPhotoArr = picArr.mutableCopy;
                };
            }
            return cell;
        }
    }
}

#pragma mark - event response
//提交申请
- (void)startPlaceAnOrder:(UIButton *)btn
{
    NSLog(@"%@",self.paraDic);
    [self.view endEditing:YES];
    btn.enabled = NO;

//    //去除空字符串的字典
//    for (NSString *key in [_paraDic allKeys]) {
//        if ([_paraDic[key] isEqual:@""] || [_paraDic[key] isEqual:[NSNull class]]) {
//            [_paraDic removeObjectForKey:key];
//        }
//    }
    //逐个判断 具体到某一项
    if (![ToolViewViewController isNotNullStr:_paraDic[kECParaDicKey_name]]) {
        [SVProgressHUD showErrorWithStatus:@"请添加渠道名称"];
        btn.enabled = YES;
        return;
    }
    if (![ToolViewViewController isNotNullStr:_paraDic[kECParaDicKey_desCribe]]) {
        [SVProgressHUD showErrorWithStatus:@"请添加渠道概况"];
         btn.enabled = YES;
        return;
    }
    if (![ToolViewViewController isNotNullStr:_paraDic[kECParaDicKey_phone]]) {
        [SVProgressHUD showErrorWithStatus:@"请添加手机号码"];
         btn.enabled = YES;
        return;
    }
    if (![ToolViewViewController isNotNullStr:_paraDic[kECParaDicKey_workPhone]]) {
        [SVProgressHUD showErrorWithStatus:@"请添加办公电话"];
         btn.enabled = YES;
        return;
    }
    if (![ToolViewViewController isNotNullStr:_paraDic[kECParaDicKey_address]]) {
        [SVProgressHUD showErrorWithStatus:@"请添加地址"];
         btn.enabled = YES;
        return;
    }
    if (![ToolViewViewController isNotNullStr:_paraDic[kECParaDicKey_name]]) {
        [SVProgressHUD showErrorWithStatus:@"请添加渠道名称"];
         btn.enabled = YES;
        return;
    }
    if (![ToolViewViewController isNotNullStr:_paraDic[kECParaDicKey_purchase]]) {
        [SVProgressHUD showErrorWithStatus:@"请添加负责人"];
         btn.enabled = YES;
        return;
    }
    if (![ToolViewViewController isNotNullStr:_paraDic[kECParaDicKey_storeNumber]]) {
        [SVProgressHUD showErrorWithStatus:@"请添加门店数量"];
         btn.enabled = YES;
        return;
    }
    if (![ToolViewViewController isNotNullStr:_paraDic[kECParaDicKey_annualOperation]]) {
        [SVProgressHUD showErrorWithStatus:@"请添加年经销额"];
         btn.enabled = YES;
        return;
    }
    if (![ToolViewViewController isNotNullStr:_paraDic[kECParaDicKey_similarBrands]]) {
        [SVProgressHUD showErrorWithStatus:@"请添加同类品牌"];
         btn.enabled = YES;
        return;
    }
    if (![ToolViewViewController isNotNullStr:_paraDic[kECParaDicKey_annualSales]]) {
        [SVProgressHUD showErrorWithStatus:@"请添加年销售额"];
         btn.enabled = YES;
        return;
    }
    if (![ToolViewViewController isNotNullStr:_paraDic[kECParaDicKey_totalExpenses]]) {
        [SVProgressHUD showErrorWithStatus:@"请添加费用总计"];
         btn.enabled = YES;
        return;
    }
    if (![ToolViewViewController isNotNullStr:_paraDic[kECParaDicKey_costStatement]]) {
        [SVProgressHUD showErrorWithStatus:@"请添加费用说明"];
         btn.enabled = YES;
        return;
    }

    //商品信息可选
    NSInteger number = 14;
    if (_moduleType == HomeModuleTypeEC) {
        if (!self.paraDic[@"approachEProductList"]) {
            number --;
        }
    }
    else {
        if (!self.paraDic[@"approachAProductList"]) {
            number --;
        }
    }
    
    if (!self.paraDic[@"photoList"]) {
        number --;
    }
    if ([self.paraDic allKeys].count >= number)//
    {
        [self.paraDic setValue:@"0" forKey:@"approvalType"];
        [self.paraDic setValue:[Singleton shareInstance].userId forKey:@"user.id"];

        if (_isChangeInfo)//修改状态
        {
            [self.paraDic setValue:_orderId forKey:@"id"];
            if (_moduleType == HomeModuleTypeEA)//申请
            {
                [self.paraDic setValue:@"1" forKey:@"approvalStatus"];
            }
            else if (_moduleType == HomeModuleTypeEC)//核销
            {
                [self.paraDic setValue:_detailInfoModel.approvalType forKey:@"approvalType"];
                [self.paraDic setValue:_orderStatus forKey:@"examineStatus"];
            }
        }
        else//首发状态
        {
            [self.paraDic setValue:@"1" forKey:@"approvalStatus"];
        }
    }
    else
    {
        [SVProgressHUD showErrorWithStatus:@"请完善信息"];
         btn.enabled = YES;
        return;
    }

    NWSaleApplyRequest *request = [[NWSaleApplyRequest alloc] init];
    [request completion:^(id result, NSString *message, id extension, BOOL succ) {
        if (succ)
        {
            btn.enabled = YES;
            [SVProgressHUD showSuccessWithStatus:@"提交成功"];
            if (self.submitComplete) {
                self.submitComplete();
            }
            if (_moduleType == HomeModuleTypeEC) {
                [self.navigationController popViewControllerAnimated:YES];
            } else {
                [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1] animated:YES];
            }
        } else {
             btn.enabled = YES;
            [SVProgressHUD showErrorWithStatus:message ?: @"网络错误"];
        }
    }];

    //改变订单状态
    if (!_isChangeInfo) {
        [self.paraDic setObject:[Singleton shareInstance].userId forKey:@"user.id"];
        [self.paraDic setObject:@"1" forKey:@"approvalStatus"];// 审批状态
        [self.paraDic setObject:@"0" forKey:@"approvalType"];// 是否拒绝 0:NO
        //        [self.paraDic setObject:[CommonTool beJsonStrWithObj:self.submitPictureArr] forKey:kECParaDicKey_photoList];
        [request startRequestCommitEnterApplyWithDic:self.paraDic];
        btn.enabled = YES;
    }
    else
    {
        if (_moduleType == HomeModuleTypeEC)
        {
            [request startRequestUpdateEnterCheckWithDic:self.paraDic];
        }
        else
        {
            [request startRequestUpdateEnterApplyWithDic:self.paraDic];
        }
        btn.enabled = YES;
    }
}

- (void)onTapLeftBarButton {
    if (self.submitComplete) {
        self.submitComplete();
    }
    [super onTapLeftBarButton];
}

#pragma mark - private method
- (NSString *)toJsonDate:(id )obj   {
    NSData *jsonDate = [NSJSONSerialization dataWithJSONObject:obj options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonStr = [[NSString alloc] initWithData:jsonDate encoding:NSUTF8StringEncoding];
    jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"    " withString:@""];
    jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"(\\n)"
                                                 withString:@"" options:NSRegularExpressionSearch
                                                      range:NSMakeRange(0, [jsonStr length])];
    jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"(\")"
                                                 withString:@"\'" options:NSRegularExpressionSearch
                                                      range:NSMakeRange(0, [jsonStr length])];
    jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"(\\)"
                                                 withString:@"" options:NSRegularExpressionSearch
                                                      range:NSMakeRange(0, [jsonStr length])];
    return jsonStr;
}

#pragma mark - getter and setter
- (NSMutableDictionary *)paraDic
{
    if (!_paraDic)
    {
        _paraDic = [NSMutableDictionary dictionary];
    }
    return _paraDic;
}

- (NSMutableArray<NSDictionary *> *)submitPictureArr {
    if (!_submitPictureArr) {
        _submitPictureArr = [NSMutableArray array];
    }
    return _submitPictureArr;
}

- (NSArray *)leftStrArr {
    if (!_leftStrArr) {
        _leftStrArr = @[
                        @"渠道名称",
                        @"渠道概况",//2 修改梯添加
                        @"手机号码",
                        @"办公电话",//4
                        @"地址",
                        @"负责人",
                        @"门店数量",
                        @"年经营额",
                        @"同类品牌",
                        @"年销售额",
                        @"费用总计",
                        @"费用说明"//12
                        ];
    }
    return _leftStrArr;
}

- (NSArray *)keysArr {
    if (!_keysArr) {
        _keysArr = @[
                     kECParaDicKey_name,
                     kECParaDicKey_desCribe,//
                     kECParaDicKey_phone,
                     kECParaDicKey_workPhone,//
                     kECParaDicKey_address,
                     kECParaDicKey_purchase,
                     kECParaDicKey_storeNumber,
                     kECParaDicKey_annualOperation,
                     kECParaDicKey_similarBrands,
                     kECParaDicKey_annualSales,
                     kECParaDicKey_totalExpenses,//
                     kECParaDicKey_costStatement
                     ];
    }
    return _keysArr;
}
    //创建第一行酷我商城单元格
- (void)createCellUIWithCell:(UITableViewCell *)cell
    {
        UIImageView *img = [UIImageView new];
        img.image = kImg(@"shangchen");
        [cell addSubview:img];
        [img mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(@15);
            make.top.equalTo(@10);
            make.size.mas_equalTo(CGSizeMake(20, 20));
        }];
        
        UILabel *lab = [UILabel new];
        lab.text = @"酷我商城";
        lab.font = KwFont(14.0);
        [cell addSubview:lab];
        [lab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(img.mas_right).offset(10);
            make.height.equalTo(@14);
            make.top.equalTo(img.mas_top);
        }];
        
        UIImageView *img2 = [UIImageView new];
        img2.image = kImg(@"next");
        [cell addSubview:img2];
        [img2 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(@-15);
            make.size.mas_equalTo(CGSizeMake(12, 15));
            make.top.equalTo(img.mas_top);
        }];
        
        UIView *lineView = [UIView new];
        lineView.backgroundColor = KwGaryColor;
        [cell addSubview:lineView];
        [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(img.mas_bottom).offset(10);
            make.left.right.equalTo(@0);
            make.height.equalTo(@1.5);
            make.bottom.equalTo(@0);
        }];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0)
    {
        //商品改变 字典变
        CargoChooseVC *vc = [[CargoChooseVC alloc] init];
        vc.changeOrderCargos = _cargoListArr;
        vc.isNotDetailModel_Order = _isNotDetailModel_Cargo;
        vc.type = CargoVCTypeOrderManage;
        vc.block = ^(NSMutableArray *cargoArr){
            _cargoListArr = [NSMutableArray arrayWithArray:cargoArr];
            _isNotDetailModel_Cargo = YES;
            NSInteger aTotalBox = 0;
            CGFloat aTotalPrice = 0;
            CGFloat totalWeight = 0;
            for (int i = 0; i<_cargoListArr.count; i++)
            {
                ESSInventoryModel *model = _cargoListArr[i];
                aTotalBox = aTotalBox + [model.totalBox integerValue];
                aTotalPrice = aTotalPrice + [model.price floatValue]*[model.totalBox integerValue];
                totalWeight = totalWeight + [model.weight integerValue]*[model.totalBox integerValue];
            }
            _totalBox = aTotalBox;
            _totalPrice = aTotalPrice;
            
            
            NSIndexSet *indeSec = [NSIndexSet indexSetWithIndex:0];
            [_tabView reloadSections:indeSec withRowAnimation:UITableViewRowAnimationAutomatic];
            
            //加参数
            [_paraDataArr removeAllObjects];
            for (int i = 0; i<cargoArr.count; i++)
            {
                ESSInventoryModel *model = cargoArr[i];
                [_paraDataArr addObject:@{kOrderItemPara_Key_ProductAttributeId:model.productAttributeId,kOrderItemPara_Key_ProductName:[NSString stringWithFormat:@"%@,%@,%@",model.productName,model.tasteName,model.specificationsName],kOrderItemPara_Key_Price:model.price,kOrderItemPara_Key_Quantity:model.totalBox,kOrderItemPara_Key_Weight:model.weight}];
            }
            NSString *dataStr = [CommonTool beJsonStrWithObj:_paraDataArr];
            
            if (_moduleType == HomeModuleTypeEC)
            {
                [_paraDic setValue:dataStr forKey:kECParaDicKey_kwApproachExamineProduct];
            }
            else
            {
                [_paraDic setValue:dataStr forKey:kECParaDicKey_approachAProductList];
            }
            
        };
        [self.navigationController pushViewController:vc animated:YES];
    }

}

@end


